<template>
  <el-upload
    :action="action"
    :before-upload="beforeAvatarUpload"
    class="avatar-uploader"
    :disabled="disabled"
    :headers="headers"
    name="fileInput"
    :on-success="handleAvatarSuccess"
    :show-file-list="false"
  >
    <img v-if="imageUrl" class="avatar" :src="imageUrl" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
</template>

<script lang="ts" setup>
  import { ref, reactive } from 'vue'
  import { ElMessage } from 'element-plus'
  import { Plus } from '@element-plus/icons-vue'
  import type { UploadProps } from 'element-plus'
  import { useUserStore } from '@/store/modules/user'
  import { baseURL } from '@/config'

  const { token } = useUserStore()
  const action = ref(`${baseURL}/WF_Document/UploadFile`)
  const headers = reactive({ Authorization: `Bearer ${token}` })

  const props = defineProps({
    imageUrl: {
      type: String,
      default: '',
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  })

  const emit = defineEmits(['success'])

  const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
  ) => {
    console.log(response.data)
    if (response.code == 200) {
      // emit('success', URL.createObjectURL(uploadFile.raw!))
      emit('success', response.data)
    }
    // imageUrl.value = URL.createObjectURL(uploadFile.raw!)
  }

  const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    // if (rawFile.type !== 'image/jpeg') {
    //   ElMessage.error('Avatar picture must be JPG format!')
    //   return false
    // } else if (rawFile.size / 1024 / 1024 > 2) {
    //   ElMessage.error('Avatar picture size can not exceed 2MB!')
    //   return false
    // }
    if (rawFile.size / 1024 / 1024 > 2) {
      ElMessage.error('Avatar picture size can not exceed 2MB!')
      return false
    }
    return true
  }
</script>

<style lang="scss" scoped>
  .avatar-uploader .avatar {
    width: 120px;
    height: 120px;
    display: block;
    ::v-deep .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }

    ::v-deep .el-upload:hover {
      border-color: var(--el-color-primary);
    }

    ::v-deep .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 120px;
      height: 120px;
      text-align: center;
    }
  }
</style>
